<template>
  <div>
    <template v-if="id">
      <el-table :data="position" v-loading="loading" size="small"
                :header-cell-style="{fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border>
        <!-- 顺序列 -->
        <el-table-column align="center" label="顺序" width="150" prop="tenantSerialNumber">
          <template slot-scope="scope">
            <span>第{{scope.row.tenantSerialNumber}}承租人</span>
          </template>
        </el-table-column>

        <!-- 承租人信息列 -->
        <el-table-column align="center" label="承租人信息" min-width="300">
          <template slot-scope="scope">
            <!-- 非编辑状态显示承租人信息 -->
            <template v-if="!scope.row.edit">
              {{ scope.row.tenantName ? `${scope.row.tenantName}_${scope.row.tenantIdCardFour}` : '-' }}
            </template>

            <!-- 编辑状态显示操作按钮 -->
            <template v-else>
              <el-button type="primary" size="mini"  @click="openLesseeDialog(scope.row)"> 选择承租人 </el-button>
              <el-button type="primary" size="mini" @click="addTem(scope.row)" style="margin-left: 10px">新增承租人</el-button>
            </template>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.status !== 0">
              <template v-if="!scope.row.edit">
                <el-button v-if="showAdd" icon="el-icon-edit" type="primary" size="mini"  @click="handlerEdit(scope.row)"
                    :disabled="isDisabled">编辑
                </el-button>
                <el-button
                    v-if="showAdd && scope.row.tenantSerialNumber>2"
                    icon="el-icon-delete" type="danger" size="mini"
                    @click="handlerDeletePosition(scope.row.id)"
                    :disabled="isDisabled">删除
                </el-button>
              </template>
              <template v-else>
                <el-button icon="el-icon-check" type="primary" size="mini"
                    @click="handlerPositionSave(scope.row)">保存
                </el-button>
                <el-button icon="el-icon-close" type="danger" size="mini"
                    @click="cancelEdit(scope.row)"
                    style="margin-left: 10px">取消
                </el-button>
              </template>
            </template>
            <template v-else>
              非正式数据（未上报或审核中）
            </template>
          </template>
        </el-table-column>
      </el-table>

      <el-row v-if="showAdd" style="margin: 10px 0;width: 100%;display: flex;justify-content: center">
        <el-button @click="addRow" type="primary" icon="el-icon-plus" circle></el-button>
      </el-row>
    </template>
    <el-result v-else icon="warning" title="提示" subTitle="请先保存基本信息再操作承租人"></el-result>

    <!-- 承租人选择弹窗 -->
    <el-dialog title="选择承租人" :visible.sync="dialogVisible" width="40%">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-input
              v-model="listPram.yhkeyword"
              placeholder="输入姓名或身份证号搜索"
              @keyup.enter="handleSearch"
              clearable>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button  icon="el-icon-search" @click="handleSearch" style="width:100%">搜索</el-button>
        </el-col>
      </el-row>

      <el-table
          :data="filteredTableData"
          border
          style="width: 100%; margin-top: 20px">
        <el-table-column align="center" prop="tenantName" label="姓名"></el-table-column>
        <el-table-column align="center" prop="tenantIdCardFour" label="身份证号"></el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
                type="primary"
                @click="selectLessee(scope.row)">确定
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增承租人弹窗 -->
    <addLessee ref="addTemplates" />
  </div>
</template>

<script>
import addLessee from "@/views/house/information/components/addLessee.vue";
import { deleteRow, getTenantRelationshipById, listNew, saveTenantRelationship } from "@/api/lessee";

export default {
  name: 'lessee',
  components: { addLessee },
  props: ['id', 'isDisabled', 'uniqueId', 'leaseCertificateNumber'],
  data() {
    return {
      position: [],
      loading: false,
      showAdd: true,
      originalData: {}, // 用于保存编辑前的原始数据

      // 承租人选择相关
      dialogVisible: false,
      currentRow: null,
      filteredTableData: [],
      tableLoading: false,
      listPram: {
        page: 1,
        limit: 10,
        yhkeyword: '',
      },
    }
  },
  mounted() {
    this.getPositionList();
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getPositionList();
        }
      }
    }
  },
  methods: {
    // 新增行
    addRow() {
      const tenantSerialNumberNew = this.position.length > 0
          ? this.position[this.position.length - 1].tenantSerialNumber + 1
          : 1;
      this.position.push({
        id: 'new_position',
        uniqueId: this.uniqueId,
        tenantSerialNumber: tenantSerialNumberNew,
        leaseCertificateNumber: this.leaseCertificateNumber,
        name: '',
        department_id: null,
        person_id: this.id,
        is_main: 2,
        is_leader: 2,
        job_level: null,
        edit: true,
      });
      this.showAdd = false;
    },

    // 进入编辑状态
    handlerEdit(row) {
      // 保存原始数据以便取消编辑时恢复
      this.originalData = {
        ...row,
        tenantName: row.tenantName,
        tenantIdCardFour: row.tenantIdCardFour
      };

      this.$set(row, 'edit', true);
      this.showAdd = false;
    },

    // 取消编辑
    cancelEdit(row) {
      // 恢复原始数据
      Object.assign(row, this.originalData);
      this.$set(row, 'edit', false);
      this.showAdd = true;
    },

    // 打开选择承租人弹窗
    openLesseeDialog(row) {
      this.currentRow = row;
      this.dialogVisible = true;
      this.listPram.yhkeyword = '';
      this.filteredTableData = [];
    },

    // 搜索承租人
    handleSearch() {
      if (!this.listPram.yhkeyword.trim()) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      this.tableLoading = true;
      listNew(this.listPram).then(res => {
        this.filteredTableData = res.list;
        if (this.filteredTableData.length === 0) {
          this.$message.info('未找到匹配结果');
        }
      }).finally(() => {
        this.tableLoading = false;
      });
    },

    // 选择承租人
    selectLessee(row) {
      this.$set(this.currentRow, 'tenantName', row.tenantName);
      this.$set(this.currentRow, 'tenantIdCard', row.tenantIdCard);
      this.dialogVisible = false;
      this.$message.success('承租人选择成功');
    },

    // 获取承租人列表
    getPositionList() {
      this.loading = true;
      getTenantRelationshipById(this.uniqueId).then(res => {
        this.position = res.map(item => ({
          ...item,
          edit: false // 初始化时设置edit为false
        }));
      }).finally(() => {
        this.loading = false;
      });
    },

    // 删除承租人
    handlerDeletePosition(id) {
      this.$confirm('确认删除当前数据').then(() => {
        this.loading = true;
        deleteRow(id).then(() => {
          this.$message.success('删除成功');
          this.getPositionList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    // 保存承租人信息
    handlerPositionSave(row) {
      this.loading = true;
      if (row.id === 'new_position') {
        delete row.id;
      }
      saveTenantRelationship(row).then(() => {
        this.$message.success('保存成功!');
        this.$set(row, 'edit', false);
        this.showAdd = true;
        this.getPositionList();
      }).finally(() => {
        this.loading = false;
      });
    },

    // 打开新增承租人弹窗
    addTem() {
      this.$refs.addTemplates.dialogVisible = true;
    }
  }
}
</script>
